package top.system.dept.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.system.dept.pojo.Item;
import top.system.dept.pojo.SysResp;
import top.system.dept.service.ItemService;
import top.system.dept.utils.RespUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName: ItemController
 * @Author: Amosen
 * @Since: 2021/5/21
 */

@Controller
@RequestMapping("/item")
@ResponseBody
public class ItemController {

    @Autowired
    ItemService itemService;

    @RequestMapping(value = "/getItem")
    public SysResp handleGetItem(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        return itemService.getItems(pageNum, pageSize);
    }

    @RequestMapping("/addItem")
    @ResponseBody
    public SysResp handleAddItem(@RequestParam("userModal") String userModal,
                                 @RequestParam("name") String itemName,
                                 @RequestParam("number") Integer itemNumber,
                                 @RequestParam("pictures") MultipartFile itemPics,
                                 HttpServletRequest request) {
        return itemService.handleAddItem(userModal, itemName, itemNumber, itemPics, request);
    }

    @RequestMapping("/updateItem")
    @ResponseBody
    public SysResp handleUpdateItem(@RequestBody Map<String, String> data) {
        String userModal = data.get("userModal");
        String itemStr = data.get("item");
        ObjectMapper om = new ObjectMapper();
        try {
            Item item = om.readValue(itemStr, Item.class);
            return itemService.updateItem(userModal, item);
        } catch (JsonProcessingException e) {
            return RespUtil.illegalParam();
        }
    }

    @RequestMapping("/count")
    @ResponseBody
    public SysResp countItem() {
        int count = itemService.countItem();
        return RespUtil.successData("count", count);
    }
}
